// 在head 中 加载 必要静态
document.write('<link rel="stylesheet" href="//cdn.jsdelivr.net/npm/mdui@0.4.3/dist/css/mdui.min.css">');

document.write('<link href="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/css/bootstrap.min.css" rel="stylesheet"></link>')

// DPlayer flv支持
document.write('<script src="https://cdn.jsdelivr.net/npm/flv.js/dist/flv.min.js"></script>')
document.write('<link href="https://cdn.jsdelivr.net/npm/dplayer/dist/DPlayer.min.css" rel="stylesheet">')
document.write('<script src="https://cdn.jsdelivr.net/npm/dplayer/dist/DPlayer.min.js"></script>')
// Google fonts支持
document.write('<link href = "https://fonts.googleapis.com/css?family=Noto+Sans+SC|Noto+Sans+TC|Sawarabi+Gothic|Source+Sans+Pro&display=swap" rel = "stylesheet" >')
// 剪切板复制支持
document.write('<script src="https://cdn.jsdelivr.net/npm/clipboard/dist/clipboard.min.js"></script>')

// markdown支持
document.write('<script src="//cdn.jsdelivr.net/npm/markdown-it@10.0.0/dist/markdown-it.min.js"></script>');
document.write("<style>.mdui-container { max-width: 980px } .mdui-list-item { transition: none } .mdui-list>.th { background-color: initial } .mdui-list-item>a { width: 100%; line-height: 3pc } .mdui-list-item { margin: 2px 0; padding: 0 } @media screen and (max-width:980px) { .mdui-list-item .mdui-text-right { display: none } .mdui-container { width: 100% !important; margin: 0 } } .m463c{ color: #6F1E51; } body { font-family: 'Noto Sans SC', sans-serif; font-family: 'Sawarabi Gothic', sans-serif; font-family: 'Noto Sans TC', sans-serif; font-family: 'Source Sans Pro', sans-serif; }</style>");
// 初始化页面，并载入必要资源
function init() {
	document.siteName = $('title').html();
	$('body').addClass("mdui-theme-primary-blue-grey mdui-theme-accent-blue");
	var myDate = new Date();
	var html = `<div style="min-height: calc(100vh - 77px);">
<header> 
<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="${"https://" + window.location.host + "/"}">
  <img src="https://cdn.jsdelivr.net/gh/gaowanliang/p/img/tx.png" width="30" height="30" class="d-inline-block align-top mdui-img-circle" alt="">
  高玩梁的网盘
  </a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>
  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item active">
        <a class="nav-link" href="${"https://" + window.location.host + "/"}">Google drive<span class="sr-only">(current)</span></a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="https://gwliang.com">博客</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="https://ariang.gwliang.com">离线下载</a>
	  </li>
      <li class="nav-item">
        <a class="nav-link" href="https://cloud.gwliang.com">Onedrive</a>
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="只是为了好看的摆设" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">搜索</button>
    </form>
  </div>
</nav>
</header>
<div id="content" class="mdui-container"> 
</div>
</div>
<div style="color: #333;background-color: #F8F9FA;padding-top: 3px;padding-bottom: 3px;text-align: center;border: 1px solid #ededed;border-color: #F8F9FA;">
	<p style="margin: 10px 0">由 <a class="m463c" href="https://workers.cloudflare.com/">Cloudflare Workers®</a> 和 <a class="m463c" href="https://www.google.com/drive">Google drive</a> 强力驱动</p>
	<p style="margin: 2px 0">高玩梁 © ${myDate.getFullYear()} </p>
</div>

<script src="https://cdn.jsdelivr.net/npm/bootstrap@4.3.1/dist/js/bootstrap.js"></script>
    
    <script src="//cdnjs.loli.net/ajax/libs/mdui/0.4.3/js/mdui.min.js"></script>
    <script>var clipboard = new ClipboardJS('.btn');
        clipboard.on('success', function (e) {
            mdui.snackbar({
                message: '复制成功'
            });
        });
        clipboard.on('error', function (e) {
            mdui.snackbar({
                message: '复制失败，请手动复制'
            });
        });
    </script>
	`;
	$('body').html(html);
}



function render(path) {
	if (path.indexOf("?") > 0) {
		path = path.substr(0, path.indexOf("?"));
	}
	title(path);
	nav(path);
	if (path.substr(-1) == '/') {
		list(path);
	} else {
		file(path);
	}
}


// 渲染 title
function title(path) {
	path = decodeURI(path);
	$('title').html(document.siteName + ' - ' + path);
}

// 渲染导航栏
function nav(path) {
	var html = "";
	html += `<a href="/" class="mdui-typo-headline folder">${document.siteName}</a>`;
	var arr = path.trim('/').split('/');
	var p = '/';
	if (arr.length > 0) {
		for (i in arr) {
			var n = arr[i];
			n = decodeURI(n);
			p += n + '/';
			if (n == '') {
				break;
			}
			html += `<i class="mdui-icon material-icons mdui-icon-dark folder" style="margin:0;">chevron_right</i><a class="folder" href="${p}">${n}</a>`;
		}
	}
	$('#nav').html(html);
}

// 渲染文件列表
function list(path) {
	var content = `
	<div id="head_md" class="mdui-typo" style="display:none;padding: 20px 0;"></div>

	 <div class="mdui-row mdui-hidden-xs-down"> 
	  <ul class="mdui-list"> 
	   <li class="mdui-list-item th"> 
	    <div class="mdui-col-xs-12 mdui-col-sm-7">
	     文件
	<i class="mdui-icon material-icons icon-sort" data-sort="name" data-order="more">expand_more</i>
	    </div> 
	    <div class="mdui-col-sm-3 mdui-text-right">
	     修改时间
	<i class="mdui-icon material-icons icon-sort" data-sort="date" data-order="downward">expand_more</i>
	    </div> 
	    <div class="mdui-col-sm-2 mdui-text-right">
	     大小
	<i class="mdui-icon material-icons icon-sort" data-sort="size" data-order="downward">expand_more</i>
	    </div> 
	    </li> 
	  </ul> 
	 </div> 
	 <div class="mdui-row mdui-hidden-xs-down"> 
	  <ul id="list" class="mdui-list"> 
	  </ul> 
	 </div>
	 <div class="mdui-container mdui-hidden-sm-up"> 
	  <ul id="mlist" class="mdui-list"> 
	  </ul> 
	 </div>
	 <div id="readme_md" class="mdui-typo" style="display:none; padding: 20px 0;"></div>
	`;
	$('#content').html(content);

	var password = localStorage.getItem('password' + path);
	$('#list').html(`<div class="mdui-progress"><div class="mdui-progress-indeterminate"></div></div>`);
	$('#mlist').html(`<div class="mdui-spinner mdui-spinner-colorful mdui-center"></div>`);
	$('#readme_md').hide().html('');
	$('#head_md').hide().html('');
	$.post(path, '{"password":"' + password + '"}', function (data, status) {
		var obj = jQuery.parseJSON(data);
		if (typeof obj != 'null' && obj.hasOwnProperty('error') && obj.error.code == '401') {
			var pass = prompt("目录加密, 请输入密码", "");
			localStorage.setItem('password' + path, pass);
			if (pass != null && pass != "") {
				list(path);
			} else {
				history.go(-1);
			}
		} else if (typeof obj != 'null') {
			list_files(path, obj.files);
		}
	});
}

function list_files(path, files) {
	html = "";
	var mhtml = '<li class="mdui-subheader-inset">文件列表</li>'
	if ("https://" + window.location.host + "/" != self.location.href) {
		html += `<li class="mdui-list-item mdui-ripple"><a href="javascript:history.back(-1)" class="folder">
	            <div class="mdui-col-xs-12 mdui-col-sm-7 mdui-text-truncate">
	            <i class="mdui-icon material-icons">file_upload</i>
	              返回上一级
	            </div>
	            <div class="mdui-col-sm-3 mdui-text-right"></div>
	            <div class="mdui-col-sm-2 mdui-text-right"></div>
	            </a>
			</li>`
		mhtml += ` <li class="mdui-list-item" onclick="location.href='javascript:history.back(-1)'">
    			<i class="mdui-list-item-avatar mdui-icon material-icons">file_upload</i>
    			<div class="mdui-list-item-content">
      			<div class="mdui-list-item-title">返回上一级</div>
      			<div class="mdui-list-item-text"></div>
				</div>
			</li>
			`
	}

	for (i in files) {
		var item = files[i];
		var p = path + item.name + '/';
		if (item['size'] == undefined) {
			item['size'] = "";
		}

		item['modifiedTime'] = utc2beijing(item['modifiedTime']);
		item['size'] = formatFileSize(item['size']);
		if (item['mimeType'] == 'application/vnd.google-apps.folder') {
			html += `<li class="mdui-list-item mdui-ripple"><a href="${p}" class="folder">
	            <div class="mdui-col-xs-12 mdui-col-sm-7 mdui-text-truncate">
	            <i class="mdui-icon material-icons">folder_open</i>
	              ${item.name}
	            </div>
	            <div class="mdui-col-sm-3 mdui-text-right">${item['modifiedTime']}</div>
	            <div class="mdui-col-sm-2 mdui-text-right">${item['size']}</div>
	            </a>
			</li>`;
			mhtml += ` <li class="mdui-list-item" onclick="location.href='${p}'">
    			<i class="mdui-list-item-avatar mdui-icon material-icons">folder</i>
    			<div class="mdui-list-item-content">
      			<div class="mdui-list-item-title">${item.name}</div>
      			<div class="mdui-list-item-text">修改时间：${item['modifiedTime']}</div>
				</div>
			</li>
			`
		} else {
			var p = path + item.name;
			var c = "file";
			if (item.name == "README.md") {
				get_file(p, item, function (data) {
					markdown("#readme_md", data);
				});
			}
			if (item.name == "HEAD.md") {
				get_file(p, item, function (data) {
					markdown("#head_md", data);
				});
			}
			var icon = "insert_drive_file"
			var ext = p.split('.').pop();
			if ("|html|php|css|go|java|js|json|txt|sh|md|mp4|flv|bmp|jpg|jpeg|png|gif|m4a|mp3|wav|ogg|webm|avi|m4v|mkv|mov|".indexOf(`|${ext}|`) >= 0) {
				p += "?a=view";
				c += " view";
				icon = filetype(`|${ext}|`, 0)
			}
			html += `<li class="mdui-list-item file mdui-ripple" target="_blank"><a gd-type="${item.mimeType}" href="${p}" class="${c}">
	          <div class="mdui-col-xs-12 mdui-col-sm-7 mdui-text-truncate">
	          <i class="mdui-icon material-icons">${icon}</i>
	            ${item.name}
	          </div>
	          <div class="mdui-col-sm-3 mdui-text-right">${item['modifiedTime']}</div>
	          <div class="mdui-col-sm-2 mdui-text-right">${item['size']}</div>
	          </a>
		  </li>`;
			mhtml += `<li class="mdui-list-item" target="_blank" onclick="location.href='${p}'">
			<i class="mdui-list-item-avatar mdui-icon material-icons mdui-color-grey-100 mdui-text-color-grey-900">${icon}</i>
			<div class="mdui-list-item-content">
			<div class="mdui-list-item-title">${item.name}</div>
			<div class="mdui-list-item-text mdui-list-item-two-line">大小:${item['size']}<br>修改时间：${item['modifiedTime']}
			</div>
			</div>
		</li>
			`
		}
	}
	$('#list').html(html);
	$('#mlist').html(mhtml);
}


function get_file(path, file, callback) {
	var key = "file_path_" + path + file['modifiedTime'];
	var data = localStorage.getItem(key);
	if (data != undefined) {
		return callback(data);
	} else {
		$.get(path, function (d) {
			localStorage.setItem(key, d);
			callback(d);
		});
	}
}

function filetype(path) {
	if ("|html|php|css|go|java|js|json|txt|sh|md|".indexOf(path) >= 0) {
		return "code"
	}

	if ("|mp4|webm|avi|flv|m4v|mkv|webm|mov|".indexOf(path) >= 0) {
		return "movie"
	}

	if ("|mp3|wav|ogg|m4a|".indexOf(path) >= 0) {
		return "music_note"
	}

	if ("|bmp|jpg|jpeg|png|gif|".indexOf(path) >= 0) {
		return "image"
	}


}

// 文件展示 ?a=view
function file(path) {
	var name = path.split('/').pop();
	var ext = name.split('.').pop().toLowerCase().replace(`?a=view`, "");
	if ("|html|php|css|go|java|js|json|txt|sh|md|".indexOf(`|${ext}|`) >= 0) {
		return file_code(path);
	}

	if ("|mp4|webm|avi|flv|m4v|".indexOf(`|${ext}|`) >= 0) {
		return file_video(path);
	}

	if ("|mp3|wav|ogg|m4a|".indexOf(`|${ext}|`) >= 0) {
		return file_audio(path);
	}

	if ("|bmp|jpg|jpeg|png|gif|".indexOf(`|${ext}|`) >= 0) {
		return file_image(path);
	}
}

// 文件展示 |html|php|css|go|java|js|json|txt|sh|md|
function file_code(path) {
	var type = {
		"html": "html",
		"php": "php",
		"css": "css",
		"go": "golang",
		"java": "java",
		"js": "javascript",
		"json": "json",
		"txt": "Text",
		"sh": "sh",
		"md": "Markdown",
	};
	var name = path.split('/').pop();
	var ext = name.split('.').pop();
	var href = window.location.origin + path;
	var content = `
<div class="mdui-container">
<pre id="editor" ></pre>
</div>
<div class="mdui-textfield">
	<label class="mdui-textfield-label">下载地址</label>
	<input class="mdui-textfield-input" type="text" value="${href}"/>
</div>
<a href="${href}" class="mdui-fab mdui-fab-fixed mdui-ripple mdui-color-theme-accent"><i class="mdui-icon material-icons">file_download</i></a>

<script src="https://cdn.staticfile.org/ace/1.4.7/ace.js"></script>
<script src="https://cdn.staticfile.org/ace/1.4.7/ext-language_tools.js"></script>
	`;
	$('#content').html(content);

	$.get(path, function (data) {
		$('#editor').html($('<div/>').text(data).html());
		var code_type = "Text";
		if (type[ext] != undefined) {
			code_type = type[ext];
		}
		var editor = ace.edit("editor");
		editor.setTheme("ace/theme/ambiance");
		editor.setFontSize(18);
		editor.session.setMode("ace/mode/" + code_type);

		//Autocompletion
		editor.setOptions({
			enableBasicAutocompletion: true,
			enableSnippets: true,
			enableLiveAutocompletion: true,
			maxLines: Infinity
		});
	});
}

// 文件展示 视频 |mp4|webm|avi|flv|m4v|mkv|mov|
function file_video(path) {
	var url = window.location.origin + path;
	var content = `
<div class="mdui-container-fluid">
	<br>
	<div id="dplayer"></div>
	<br>
	<!-- 固定标签 -->
	<div class="card text-center">
		<div class="card-header">
			<ul class="nav nav-tabs card-header-tabs">
				<li class="nav-item">
					<a class="nav-link active" data-toggle="tab" id="dl-tab" href="#dl">下载地址</a>
				</li>
				<li class="nav-item">
					<a class="nav-link" data-toggle="tab" id="hl-tab" href="#hl">HTML 引用地址</a>
				</li>
			</ul>
		</div>
		<div class="tab-content" id="myTabContent">
			<div class="tab-pane card-body fade show active" id="dl" role="tabpanel" aria-labelledby="dl-tab">
				<h5 class="card-title">下载地址</h5>
				<p class="card-text">${url}</p>
				<button
					data-clipboard-text="${url}"
					class="btn btn-primary">复制到剪切板</button>
			</div>
			<div class="tab-pane card-body fade" id="hl" role="tabpanel" aria-labelledby="hl-tab">
				<h5 class="card-title">HTML 引用地址</h5>
				<p class="card-text" id="TAT">TAT</p>
				<button
					data-clipboard-text='<video><source src="${url}" type="video/mp4"></video>'
					class="btn btn-primary">复制到剪切板</button>
			</div>
		</div>
	</div>
			<br>
<a href="${url}" class="mdui-fab mdui-fab-fixed mdui-ripple mdui-color-theme-accent"><i class="mdui-icon material-icons">file_download</i></a>
	
	`;
	$('#content').html(content);
	$('#TAT').text(`<video><source src="${url}" type="video/mp4"></video>`);
	const dp = new DPlayer({
		container: document.getElementById('dplayer'),
		hotkey: true,                                                      // 可选，绑定热键，包括左右键和空格，默认值：true
		preload: 'auto',
		video: {
			url: url,
		}
	});
}

// 文件展示 音频 |mp3|m4a|wav|ogg|
function file_audio(path) {
	var url = window.location.origin + path;
	var content = `
<div class="mdui-container-fluid">
	<br>
	<audio class="mdui-center" preload controls>
	  <source src="${url}"">
	</audio>
	<br>
	<!-- 固定标签 -->

<div class="card text-center">
		<div class="card-header">
			<ul class="nav nav-tabs card-header-tabs">
				<li class="nav-item">
					<a class="nav-link active" data-toggle="tab" id="dl-tab" href="#dl">下载地址</a>
				</li>
				<li class="nav-item">
					<a class="nav-link" data-toggle="tab" id="hl-tab" href="#hl">HTML 引用地址</a>
				</li>
			</ul>
		</div>
		<div class="tab-content" id="myTabContent">
			<div class="tab-pane card-body fade show active" id="dl" role="tabpanel" aria-labelledby="dl-tab">
				<h5 class="card-title">下载地址</h5>
				<p class="card-text">${url}</p>
				<button
					data-clipboard-text="${url}"
					class="btn btn-primary">复制到剪切板</button>
			</div>
			<div class="tab-pane card-body fade" id="hl" role="tabpanel" aria-labelledby="hl-tab">
				<h5 class="card-title">HTML 引用地址</h5>
				<p class="card-text" id="TAT">TAT</p>
				<button
					data-clipboard-text='<audio><source src="${url}"></audio>'
					class="btn btn-primary">复制到剪切板</button>
			</div>
		</div>
	</div>
			<br>

	
<a href="${url}" class="mdui-fab mdui-fab-fixed mdui-ripple mdui-color-theme-accent"><i class="mdui-icon material-icons">file_download</i></a>
	`;
	$('#content').html(content);
	$('#TAT').text(`<audio><source src="${url}"></audio>`);
}


// 图片展示
function file_image(path) {
	var url = window.location.origin + path;
	var content = `
<div class="mdui-container-fluid">
	<br>
	<img class="mdui-img-fluid" src="${url}"/>
	<br>

<div class="card text-center">
		<div class="card-header">
			<ul class="nav nav-tabs card-header-tabs">
				<li class="nav-item">
					<a class="nav-link active" data-toggle="tab" id="dl-tab" href="#dl">下载地址</a>
				</li>
				<li class="nav-item">
					<a class="nav-link" data-toggle="tab" id="hl-tab" href="#hl">HTML 引用地址</a>
				</li>
				<li class="nav-item">
					<a class="nav-link" data-toggle="tab" id="ml-tab" href="#ml">Markdown 引用地址</a>
				</li>
			</ul>
		</div>
		<div class="tab-content" id="myTabContent">
			<div class="tab-pane card-body fade show active" id="dl" role="tabpanel" aria-labelledby="dl-tab">
				<h5 class="card-title">下载地址</h5>
				<p class="card-text">${url}</p>
				<button
					data-clipboard-text="${url}"
					class="btn btn-primary">复制到剪切板</button>
			</div>
			<div class="tab-pane card-body fade" id="hl" role="tabpanel" aria-labelledby="hl-tab">
				<h5 class="card-title">HTML 引用地址</h5>
				<p class="card-text" id="TAT">TAT</p>
				<button
					data-clipboard-text="<img src='${url}' />"
					class="btn btn-primary">复制到剪切板</button>
			</div>
			<div class="tab-pane card-body fade" id="ml" role="tabpanel" aria-labelledby="ml-tab">
				<h5 class="card-title">HTML 引用地址</h5>
				<p class="card-text" id="TAT">![](${url})</p>
				<button
					data-clipboard-text='![](${url})'
					class="btn btn-primary">复制到剪切板</button>
			</div>
		</div>
	</div>
			<br>



<a href="${url}" class="mdui-fab mdui-fab-fixed mdui-ripple mdui-color-theme-accent"><i class="mdui-icon material-icons">file_download</i></a>
	`;
	$('#content').html(content);
	$('#TAT').text(`<img src='${url}' />`);
}


//时间转换
function utc2beijing(utc_datetime) {
	// 转为正常的时间格式 年-月-日 时:分:秒
	var T_pos = utc_datetime.indexOf('T');
	var Z_pos = utc_datetime.indexOf('Z');
	var year_month_day = utc_datetime.substr(0, T_pos);
	var hour_minute_second = utc_datetime.substr(T_pos + 1, Z_pos - T_pos - 1);
	var new_datetime = year_month_day + " " + hour_minute_second; // 2017-03-31 08:02:06

	// 处理成为时间戳
	timestamp = new Date(Date.parse(new_datetime));
	timestamp = timestamp.getTime();
	timestamp = timestamp / 1000;

	// 增加8个小时，北京时间比utc时间多八个时区
	var unixtimestamp = timestamp + 8 * 60 * 60;

	// 时间戳转为时间
	var unixtimestamp = new Date(unixtimestamp * 1000);
	var year = 1900 + unixtimestamp.getYear();
	var month = "0" + (unixtimestamp.getMonth() + 1);
	var date = "0" + unixtimestamp.getDate();
	var hour = "0" + unixtimestamp.getHours();
	var minute = "0" + unixtimestamp.getMinutes();
	var second = "0" + unixtimestamp.getSeconds();
	return year + "-" + month.substring(month.length - 2, month.length) + "-" + date.substring(date.length - 2, date.length)
		+ " " + hour.substring(hour.length - 2, hour.length) + ":"
		+ minute.substring(minute.length - 2, minute.length) + ":"
		+ second.substring(second.length - 2, second.length);
}

// bytes自适应转换到KB,MB,GB
function formatFileSize(bytes) {
	if (bytes >= 1000000000) { bytes = (bytes / 1000000000).toFixed(2) + ' GB'; }
	else if (bytes >= 1000000) { bytes = (bytes / 1000000).toFixed(2) + ' MB'; }
	else if (bytes >= 1000) { bytes = (bytes / 1000).toFixed(2) + ' KB'; }
	else if (bytes > 1) { bytes = bytes + ' bytes'; }
	else if (bytes == 1) { bytes = bytes + ' byte'; }
	else { bytes = ''; }
	return bytes;
}

String.prototype.trim = function (char) {
	if (char) {
		return this.replace(new RegExp('^\\' + char + '+|\\' + char + '+$', 'g'), '');
	}
	return this.replace(/^\s+|\s+$/g, '');
};


// README.md HEAD.md 支持
function markdown(el, data) {
	if (window.md == undefined) {
		//$.getScript('https://cdn.jsdelivr.net/npm/markdown-it@10.0.0/dist/markdown-it.min.js',function(){
		window.md = window.markdownit();
		markdown(el, data);
		//});
	} else {
		var html = md.render(data);
		$(el).show().html(html);
	}
}

// 监听回退事件
window.onpopstate = function () {
	var path = window.location.pathname;
	render(path);
}


$(function () {
	init();
	var path = window.location.pathname;
	$("body").on("click", '.folder', function () {
		var url = $(this).attr('href');
		history.pushState(null, null, url);
		render(url);
		return false;
	});

	$("body").on("click", '.view', function () {
		var url = $(this).attr('href');
		history.pushState(null, null, url);
		render(url);
		return false;
	});

	render(path);
});
